package com.knowswift.issues.task;

import com.knowswift.common.bean.issue.po.MonitorDevice;
import com.knowswift.common.bean.project.po.Module;
import com.knowswift.common.common.GlobalProperty;
import com.knowswift.issues.service.ModuleService;
import com.knowswift.issues.service.MonitorDeviceService;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

@Component
@EnableScheduling
@EnableAsync
public class ScheduledTask {

    @Resource
    private ModuleService moduleService;

    @Resource
    private MonitorDeviceService monitorDeviceService;


//    @Scheduled(cron = "0 * * * * *")
//    public void check() {
//
//    }

    @Scheduled(cron = "0 */8 * * * ?")
    public void checkMonitorDeviceError() {

        List<MonitorDevice> list = monitorDeviceService.list();
        List<Module> modules = moduleService.list();
//        System.out.println(list);
//        System.out.println(modules);

        List<MonitorDevice> updateMonitorDeviceList = new ArrayList<>();
        for (MonitorDevice monitorDevice : list) {
            String moduleName = monitorDevice.getModuleName();
            Module module = modules.stream().filter(md -> md.getModuleName().equals(moduleName)).findAny().orElse(null);
//            System.out.println(module);
            if (module == null) {
                continue;
            }

            Integer monitorInterval = module.getMonitorInterval();
            monitorInterval=monitorInterval == null?360:monitorInterval;
            monitorInterval += 5;

            LocalDateTime lastMessageTime = monitorDevice.getLastMessageTime();
            lastMessageTime = lastMessageTime==null?monitorDevice.getCreateTime():lastMessageTime;
//            System.out.println(ChronoUnit.MINUTES.between(lastMessageTime, LocalDateTime.now()));
            if (ChronoUnit.MINUTES.between(lastMessageTime, LocalDateTime.now()) >= monitorInterval) {
                MonitorDevice newMonitorDevice = new MonitorDevice();
                newMonitorDevice.setDeviceId(monitorDevice.getDeviceId());
                newMonitorDevice.setDeviceStatus(GlobalProperty.DEVICE_STATUS_ERROR);

                updateMonitorDeviceList.add(newMonitorDevice);
            }
        }

        monitorDeviceService.updateBatchById(updateMonitorDeviceList);
    }
}
